package database.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import model.Game;
import database.util.ConnectionUtil;
import database.util.Tables;

public class GameDao {
	public static Game[] getAllGames(){
		Connection con = null;
		PreparedStatement psmt = null;
		ResultSet rs = null;
		ArrayList<Game> games = new ArrayList<Game>();
		try {
			con = ConnectionUtil.getConnection();
			String sql = "select * from " + Tables.GAME + " order by name";
			psmt = con.prepareStatement(sql);
			rs = psmt.executeQuery();
			while(rs.next()) {
				int id = rs.getInt("id");
				String name = rs.getString("name");
				String pic = rs.getString("pic");
				Game g = new Game(name, pic, id);
				games.add(g);
			}
			return games.toArray(new Game[games.size()]);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		finally {
			try {
				if(rs != null) {
					rs.close();
				}
				if(psmt != null) {
					psmt.close();
				}
				if(con != null) {
					con.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	public static Game getGameById(int id) {
		Connection con = null;
		PreparedStatement psmt = null;
		ResultSet rs = null;
		Game g = null;
		try {
			con = ConnectionUtil.getConnection();
			String sql = "select * from " + Tables.GAME + " where id = ?";
			psmt = con.prepareStatement(sql);
			psmt.setInt(1, id);
			rs = psmt.executeQuery();
			if(rs.next()) {
				String name = rs.getString("name");
				String pic = rs.getString("pic");
				g = new Game(name, pic, id);
			}
			return g;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		finally {
			try {
				if(rs != null) {
					rs.close();
				}
				if(psmt != null) {
					psmt.close();
				}
				if(con != null) {
					con.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
